package cn.chengpengper.domain.strategy.model;

import cn.chengpengper.types.common.Constants;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*@formatter:off*/

/**
 * ____________________
 * < 神兽护体，永无bug! >
 * --------------------
 *
 * @author huchengpeng
 * @version v1.0.0
 * @date 2024/7/27 10:58
 * @description 策略规则实体
 */

/*@formatter:on*/

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrategyRuleEntity {

    /**
     * 抽奖策略ID
     */
    private Long strategyId;

    /**
     * 奖品ID,规则类型为策略则不需要奖品id
     */
    private Integer awardId;

    /**
     * 规则类型：1-策略规则；2-奖品规则
     */
    private Integer ruleType;

    /**
     * 规则模型，rule_random - 随机值计算、rule_block - 抽奖几次后解锁、rule_luck_award - 幸运奖(兜底奖品)
     */
    private String ruleModel;

    /**
     * 规则概率
     */
    private String ruleValue;

    /**
     * 规则描述
     */
    private String ruleDesc;

    /**
     * 获取规则的权重值
     * 数据示例：4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     *
     * @return 权重值
     */
    public Map<String, List<Integer>> getRuleWeightValues() {
        if (!"rule_weight".equals(ruleModel)) {
            return null;
        }

        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<String, List<Integer>> resultMap = new HashMap<>(ruleValueGroups.length);
        for (String ruleValueGroup : ruleValueGroups) {
            // ruleValueGroup 示例：6000:102,103,104,105,106,107,108,109
            // 检查参数是否为空
            if (StringUtils.isBlank(ruleValueGroup)) {
                return resultMap;
            }
            String[] parts = ruleValueGroup.split(Constants.COLON);
            // parts:[6000,102,103,104,105,106,107,108,109]
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule value invalid input format " + ruleValueGroup);
            }
            // 解析值
            String[] valueStrings = parts[1].split(Constants.SPLIT);
            // valueStrings:[102,103,104,105,106,107,108,109]
            List<Integer> values = new ArrayList<>();
            for (String valueString : valueStrings) {
                values.add(Integer.parseInt(valueString));
            }
            resultMap.put(ruleValueGroup, values);
        }
        return resultMap;
    }
}
